package com.example.zhu.service.Impl;

import com.example.zhu.config.BaseContext;
import com.example.zhu.dto.OrderDTO;
import com.example.zhu.entity.*;
import com.example.zhu.mapper.*;
import com.example.zhu.result.Result;
import com.example.zhu.service.OrderService;
import com.example.zhu.utils.RegularExpression;
import com.example.zhu.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private HelperMapper helperMapper;
    @Autowired
    private ManageMapper manageMapper;
    @Autowired
    private ManageBookMapper manageBookMapper;
    @Autowired
    private TakeOrderMapper takeOrderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderCountMapper orderCountMapper;

    @Autowired
    private FakeMapper fakeMapper;

    @Autowired
    private CouponMapper couponMapper;

    private String basePath = "C:/orderImgs/";

    private String serverPath = "http://tinycnc.cn/user/order/download?url=";

    @Override
    public List<OrderVO> getAll() {
//        List<OrderVO> list = orderMapper.selectAll();
//        return list;
        return null;
    }

    @Override
    public OrderVO getEditInfo(Integer id) {
        OrderVO orderVO = orderMapper.getEditInfo(id);
        return orderVO;
    }


    @Transactional
    public void updateEditInfo(OrderDTO orderDTO) {
        orderMapper.updateEditInfo(orderDTO);
        orderDetailMapper.updatePhoneAndAddress(orderDTO);

    }

    @Override
    public List<OrderVO> selectByNumber(String number, String phone, String outPhone) {
        List<OrderVO> list = orderMapper.selectByNumberAndPhone(number, phone, outPhone);
        return list;
    }

    /**
     * 获得所有的订单信息
     *
     * @param id
     * @return
     */
    @Transactional
    public OrderMaxVO getAllInfo(Integer id) {
        OrderMaxVO orderMaxVORes = new OrderMaxVO();
//        OrderMaxVO orderMaxVO = orderMapper.selectAllInfo(id);
        OrderMaxVO orderMaxVO = orderMapper.selectInfo(id);

        Integer isUseCoupon = orderMaxVO.getIsUseCoupon();

        if (isUseCoupon != null && isUseCoupon == 1) {
            Coupon coupon = couponMapper.selectByCouponId(orderMaxVO.getCouponId());
            orderMaxVO.setName(coupon.getName());
            Double value = (double) coupon.getValue();
            double v = value / 100;
            orderMaxVO.setValue(v);
        }

        if (orderMaxVO != null) {
            BeanUtils.copyProperties(orderMaxVO, orderMaxVORes);
            Long number = orderMaxVO.getNumber();
            TakeOrders takeOrders = takeOrderMapper.selectByNumber(number);
            if (takeOrders != null) {
                LocalDateTime takeTime = takeOrders.getTakeTime();
                LocalDateTime deliveryTime = takeOrders.getDeliveryTime();
                LocalDateTime takeorderTime = takeOrders.getTakeorderTime();
                String openid = takeOrders.getOpenid();
//            BeanUtils.copyProperties(takeOrders,orderMaxVORes);
//                orderMaxVORes.setTakeOpenid(openid);
                orderMaxVORes.setDeliveryTime(deliveryTime);
                orderMaxVORes.setTakeTime(takeTime);
                orderMaxVORes.setTakeOrderTime(takeorderTime);
                AddressBook addressBook = addressBookMapper.selectByOpenid(openid);
                if (addressBookMapper != null) {
                    String takeAddress = addressBook.getAddress();
                    String takePhone = addressBook.getPhone();
                    orderMaxVORes.setTakeAddress(takeAddress);
                    orderMaxVORes.setTakePhone(takePhone);
                }
            }
        }

        Integer count = orderMaxVORes.getCount();
        List<OrderCount> orderCounts = orderCountMapper.selectByOrderId(id);
        List<OrderCount> orderCountsRes = new ArrayList<>();

        if (count == null) {
            return null;
        }

        if (orderCounts.size() == 0 || orderCounts == null) {
            for (int i = 0; i < count; i++) {
                OrderCount orderCount = OrderCount.builder()
                        .id(null)
                        .takeCode("")
                        .takeStatus(2)
                        .orderId(null)
                        .build();
                orderCountsRes.add(orderCount);
            }
        } else if (orderCounts.size() < count) {
            Integer res = count - orderCounts.size();
            for (Integer i = 0; i < res; i++) {
                OrderCount orderCount = OrderCount.builder()
                        .id(null)
                        .takeCode("")
                        .takeStatus(2)
                        .orderId(null)
                        .helperRemark("")
                        .serverRemark("")
                        .build();
                orderCountsRes.add(orderCount);
            }
        } else {
            for (OrderCount orderCount : orderCounts) {
                orderCountsRes.add(orderCount);
            }
        }

        orderMaxVORes.setOrderCounts(orderCountsRes);
        String imageOver = orderMaxVO.getImageOver();
        if (imageOver != null) {
            imageOver = "http://tinycnc.cn/user/order/download?url=" + imageOver;
            orderMaxVORes.setImageOver(imageOver);
        } else {
            orderMaxVORes.setImageOver(null);
        }

        List<String> list = orderMapper.selectImgs(id);

        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                String s = list.get(i);
                if (s != null) {
                    s = "http://tinycnc.cn/user/order/download?url=" + s;
                }
                list.set(i, s);
            }
        } else {
            orderMaxVORes.setImgUrls(null);
        }


        orderMaxVORes.setImgUrls(list);
        orderMaxVORes.setOpenid(null);
        orderMaxVORes.setTakeOpenid(null);
//        orderMaxVORes.setCouponId(null);

        return orderMaxVORes;
    }

    /**
     * 查询所有接单信息
     *
     * @return
     */
    public HistoryOrderVO selectAll() {

        HistoryOrderVO historyOrderVO = new HistoryOrderVO();
        String key = BaseContext.getCurrentUsername();
        Manage manage = helperMapper.selectByTakeKey(key);

        List<OrderVOMax> res = new ArrayList<>();
        if (manage != null) {
            Integer id = manage.getId();
            historyOrderVO.setType(0);
            long start = start();
            values1(historyOrderVO, res, id);
            long end = end();
            System.out.println("总计用时" + (end - start));
        } else {
            Manage manage_ = helperMapper.seletBySendKey(key);
            if (manage_ != null) {
                Integer id = manage_.getId();
                historyOrderVO.setType(1);
                values2(historyOrderVO, res, id);
            } else {
                return null;
            }
        }

        historyOrderVO.setTakeOrderList(res);
        return historyOrderVO;
    }

    /**
     * 查询某地区的信息
     *
     * @param path
     * @return
     */
    public AddressVO selectAllOrders(String path) {

        String key_ = BaseContext.getCurrentUsername();
        Manage manage = helperMapper.selectByTakeKey(key_);
        if (manage != null) {
            List<OrderVOMax> res = new ArrayList<>();

            //查询所有已接的订单
            List<OrderVOMax> orderVOMaxes = selectAllOrders1();

            /**
             * 统计有效订单数量
             */
            for (OrderVOMax orderVOMax : orderVOMaxes) {
                Long id1 = orderVOMax.getId();
                List<OrderCount> orderCounts = orderCountMapper.selectEffective(id1);
                if (orderCounts == null || orderCounts.size() == 0) {
                    orderVOMax.setEffectiveCount(0);
                } else {
                    orderVOMax.setEffectiveCount(orderCounts.size());
                }
            }

            for (OrderVOMax orderVOMax : orderVOMaxes) {
                String address = orderVOMax.getAddress();
                String[] split = address.split("/");
                String addr = split[0];
                if (addr.equals(path)) {
                    res.add(orderVOMax);
                }
            }

            Map<String, Integer> totals = new LinkedHashMap<>();
            Map<String, Integer> effectives = new LinkedHashMap<>();
            String[] areas = {"一层", "二层", "三层", "四层", "五层", "六层", "楼下"};

            for (String area : areas) {
                totals.put(area, 0);
                effectives.put(area, 0);
            }

            Map<String, Map<String, Integer>> category = new LinkedHashMap<>();

            LinkedHashMap<String, Integer> value1 = new LinkedHashMap<>();
            value1.put("total", 0);
            value1.put("collected", 0);
            value1.put("available", 0);
            LinkedHashMap<String, Integer> value2 = new LinkedHashMap<>();
            value2.put("total", 0);
            value2.put("collected", 0);
            value2.put("available", 0);
            LinkedHashMap<String, Integer> value3 = new LinkedHashMap<>();
            value3.put("total", 0);
            value3.put("collected", 0);
            value3.put("available", 0);
            LinkedHashMap<String, Integer> value4 = new LinkedHashMap<>();
            value4.put("total", 0);
            value4.put("collected", 0);
            value4.put("available", 0);
            LinkedHashMap<String, Integer> value5 = new LinkedHashMap<>();
            value5.put("total", 0);
            value5.put("collected", 0);
            value5.put("available", 0);

            category.put("yd8", value1);
            category.put("other", value2);
            category.put("s3d41", value3);
            category.put("s2d38", value4);
            category.put("cabinet", value5);


            Set<String> keySet = totals.keySet();
            for (OrderVOMax re : res) {
                List<OrderCount> orderCounts = re.getOrderCounts();
                Integer orderStatus = re.getOrderStatus();
                String address = re.getAddress();
                String[] split = address.split("/");
                if (orderCounts == null || orderCounts.size() == 1) {

                    OrderCount orderCount = orderCounts.get(0);
                    String takeCode = orderCount.getTakeCode();

                    if (RegularExpression.kf(takeCode)) {
                        category.compute("other", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus_ = orderStatus;
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus_ == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus_ == 25 || orderStatus_ == -25) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("collected") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                    } else if (RegularExpression.yd8(takeCode) || RegularExpression.sf(takeCode) || RegularExpression.pdd(takeCode) || RegularExpression.jd(takeCode)) {
                        category.compute("yd8", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus_ = orderStatus;
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus_ == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus_ == 21 || orderStatus_ == -21) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                    } else if (RegularExpression.s3d41(takeCode)) {
                        category.compute("s3d41", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus_ = orderStatus;
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus_ == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }

                                if (orderStatus_ == 22 || orderStatus_ == -22) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                    } else if (RegularExpression.s2d38(takeCode)) {
                        category.compute("s2d38", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus_ = orderStatus;
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus_ == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus_ == 23 || orderStatus_ == -23) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                    } else if (RegularExpression.cabinet(takeCode)) {
                        category.compute("cabinet", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus_ = orderStatus;
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus_ == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus_ == 24 || orderStatus_ == -24) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                    }

                    if (split.length == 2) {
                        String add = split[1];
                        for (String key : keySet) {
                            if (add.equals(key)) {
                                totals.put(key, totals.get(key) + 1);
                                if (orderStatus == 3) {
                                    effectives.put(key, effectives.get(key) + 1);
                                }
                            }
                        }
                    } else {
                        String add = split[2];
                        int num = Integer.parseInt(add);
                        num = num / 100;
                        switch (num) {

                            case 1: {
                                totals.put("一层", totals.get("一层") + 1);
                                if (orderStatus == 3) {
                                    effectives.put("一层", effectives.get("一层") + 1);
                                }
                                break;
                            }
                            case 2: {
                                totals.put("二层", totals.get("二层") + 1);
                                if (orderStatus == 3) {
                                    effectives.put("二层", effectives.get("二层") + 1);
                                }
                                break;
                            }

                            case 3: {
                                totals.put("三层", totals.get("三层") + 1);
                                if (orderStatus == 3) {
                                    effectives.put("三层", effectives.get("三层") + 1);
                                }
                                break;
                            }

                            case 4: {
                                totals.put("四层", totals.get("四层") + 1);
                                if (orderStatus == 3) {
                                    effectives.put("四层", effectives.get("四层") + 1);
                                }
                                break;
                            }
                            case 5: {
                                totals.put("五层", totals.get("五层") + 1);
                                if (orderStatus == 3) {
                                    effectives.put("五层", effectives.get("五层") + 1);
                                }
                                break;
                            }
                            case 6: {
                                totals.put("六层", totals.get("六层") + 1);
                                if (orderStatus == 3) {
                                    effectives.put("六层", effectives.get("六层") + 1);
                                }
                                break;
                            }
                        }
                    }
                }
            }


            AddressVO addressVO = new AddressVO();
            for (int i = 0; i < res.size() - 1; i++) {
                for (int j = 0; j < res.size() - i - 1; j++) {
                    OrderVOMax orderVOMax = res.get(j);
                    OrderVOMax orderVOMax_ = res.get(j + 1);
                    String address = orderVOMax.getAddress();
                    String address_ = orderVOMax_.getAddress();
                    String[] split = address.split("/");
                    String[] split_ = address_.split("/");
                    String num;
                    String num_;
                    int number = Integer.MAX_VALUE;
                    int number_ = Integer.MAX_VALUE;
                    if (split_.length >= 3) {
                        num_ = split_[2];
                        number_ = Integer.parseInt(num_);
                    }
                    if (split.length >= 3) {
                        num = split[2];
                        number = Integer.parseInt(num);
                    }
                    if (number > number_) {
                        OrderVOMax t = res.get(j);
                        OrderVOMax t_ = res.get(j + 1);
                        res.set(j, t_);
                        res.set(j + 1, t);
                    }
                }
            }
            addressVO.setTakeOrderList(res);
            addressVO.setTotals(totals);
            addressVO.setEffectives(effectives);
            addressVO.setCategory(category);
            return addressVO;
        } else {
            Manage manage_ = helperMapper.seletBySendKey(key_);
            if (manage_ != null) {
                List<OrderVOMax> res = new ArrayList<>();

                //查询所有已接的订单
                List<OrderVOMax> orderVOMaxes = selectAllOrders1();

                /**
                 * 统计有效订单数量
                 */

                if(orderVOMaxes == null){
                    return null;
                }

                for (OrderVOMax orderVOMax : orderVOMaxes) {
                    Long id1 = orderVOMax.getId();
                    List<OrderCount> orderCounts = orderCountMapper.selectEffective(id1);
                    if (orderCounts == null || orderCounts.size() == 0) {
                        orderVOMax.setEffectiveCount(0);
                    } else {
                        orderVOMax.setEffectiveCount(orderCounts.size());
                    }
                }

                List<OrderVOMax> orders = new ArrayList<>();
                for (OrderVOMax orderVOMax : orderVOMaxes) {
                    if (orderVOMax.getId() > 0) {
                        orders.add(orderVOMax);
                    }
                }


                for (OrderVOMax orderVOMax : orders) {
                    String address = orderVOMax.getAddress();
                    String[] split = address.split("/");
                    String addr = split[0];
                    if (addr.equals(path)) {
                        res.add(orderVOMax);
                    }
                }

                List<OrderVOMax> res_ = new ArrayList<>();
                for (OrderVOMax orderVOMax : orderVOMaxes) {
                    String address = orderVOMax.getAddress();
                    String[] split = address.split("/");
                    String addr = split[0];
                    if (addr.equals(path) && orderVOMax.getOrderStatus() == 3) {
                        res_.add(orderVOMax);
                    }
                }

                Map<String, Integer> totals = new LinkedHashMap<>();
//                Map<String, Integer> effectives = new LinkedHashMap<>();
                String[] areas = {"一层", "二层", "三层", "四层", "五层", "六层", "楼下"};

                for (String area : areas) {
                    totals.put(area, 0);
//                    effectives.put(area, 0);
                }

                Set<String> keySet = totals.keySet();
//                Set<String> keySet = effectives.keySet();
                for (OrderVOMax re : res_) {
                    List<OrderCount> orderCounts = re.getOrderCounts();
                    Integer orderStatus = re.getOrderStatus();
                    String address = re.getAddress();
                    String[] split = address.split("/");
                    if (orderCounts == null || orderCounts.size() == 1) {


                        if (split.length == 2) {
                            String add = split[1];
                            for (String key : keySet) {
                                if (add.equals(key)) {
                                    if (orderStatus == 3) {
//                                    effectives.put(key, effectives.get(key) + 1);
                                        totals.put(key, totals.get(key) + 1);
                                    }
                                }
                            }
                        } else {
                            String add = split[2];
                            int num = Integer.parseInt(add);
                            num = num / 100;
                            switch (num) {
                                case 1: {
//                                    totals.put("一层", totals.get("一层") + 1);
                                    if (orderStatus == 3) {
                                        totals.put("一层", totals.get("一层") + 1);
                                    }
                                    break;
                                }
                                case 2: {
//                                    totals.put("二层", totals.get("二层") + 1);
                                    if (orderStatus == 3) {
                                        totals.put("二层", totals.get("二层") + 1);
                                    }
                                    break;
                                }

                                case 3: {
//                                    totals.put("三层", totals.get("三层") + 1);
                                    if (orderStatus == 3) {
                                        totals.put("三层", totals.get("三层") + 1);
                                    }
                                    break;
                                }

                                case 4: {
//                                    totals.put("四层", totals.get("四层") + 1);
                                    if (orderStatus == 3) {
                                        totals.put("四层", totals.get("四层") + 1);
                                    }
                                    break;
                                }
                                case 5: {
//                                    totals.put("五层", totals.get("五层") + 1);
                                    if (orderStatus == 3) {
                                        totals.put("五层", totals.get("五层") + 1);
                                    }
                                    break;
                                }
                                case 6: {
//                                    totals.put("六层", totals.get("六层") + 1);
                                    if (orderStatus == 3) {
                                        totals.put("六层", totals.get("六层") + 1);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }

                AddressVO addressVO = new AddressVO();
                for (int i = 0; i < res.size() - 1; i++) {
                    for (int j = 0; j < res.size() - i - 1; j++) {
                        OrderVOMax orderVOMax = res.get(j);
                        OrderVOMax orderVOMax_ = res.get(j + 1);
                        String address = orderVOMax.getAddress();
                        String address_ = orderVOMax_.getAddress();
                        String[] split = address.split("/");
                        String[] split_ = address_.split("/");
                        String num;
                        String num_;
                        int number = Integer.MAX_VALUE;
                        int number_ = Integer.MAX_VALUE;
                        if (split_.length >= 3) {
                            num_ = split_[2];
                            number_ = Integer.parseInt(num_);
                        }
                        if (split.length >= 3) {
                            num = split[2];
                            number = Integer.parseInt(num);
                        }
                        if (number > number_) {
                            OrderVOMax t = res.get(j);
                            OrderVOMax t_ = res.get(j + 1);
                            res.set(j, t_);
                            res.set(j + 1, t);
                        }
                    }
                }
                addressVO.setTakeOrderList(res);
                addressVO.setTotals(totals);
//                addressVO.setEffectives(effectives);
                return addressVO;
            }


        }
        return null;
    }


    private void values2(HistoryOrderVO historyOrderVO, List<OrderVOMax> res, Integer id) {

        //查询地区
        List<String> areas = new ArrayList<>();
        historyOrderVO.setAreas(areas);

        areas = manageBookMapper.selectInfo(id);
        if (areas != null) {
            areas.sort(Comparator.comparingInt(a -> Integer.parseInt(getNum(a))));
            historyOrderVO.setAreas(areas);
        }

        historyOrderVO.setBuildsType(0);

        if (areas.size() != 28) {
            historyOrderVO.setBuildsType(1);
        } else {
            areas.stream().forEach(s -> {
                String substring = s.substring(0, 2);
                if (!substring.equals("静园")) {
                    historyOrderVO.setBuildsType(1);
                }
            });
        }

        //查询所有已接的订单
        List<OrderVOMax> orderVOMaxes = selectAllOrders();
        List<HistoryOrderVO.Build> builds = new ArrayList<>();

        if (orderVOMaxes == null) {
            return;
        }

        for (String area : areas) {
            Integer index = res.size();
//            System.out.println(index);

            for (OrderVOMax orderVOMax : orderVOMaxes) {
                String address = orderVOMax.getAddress();
                String[] split = address.split("/");
                String addr = split[0];
                if (addr.equals(area)) {
                    res.add(orderVOMax);
                }
            }
            //  TODO 二层地址 如何排序
            for (int i = index; i < res.size() - 1; i++) {
                for (int j = index; j < res.size() + index - i - 1; j++) {
                    OrderVOMax orderVOMax = res.get(j);
                    OrderVOMax orderVOMax_ = res.get(j + 1);
                    String address = orderVOMax.getAddress();
                    String address_ = orderVOMax_.getAddress();
                    String[] split = address.split("/");
                    String[] split_ = address_.split("/");
                    String num;
                    String num_;
                    int number = Integer.MAX_VALUE;
                    int number_ = Integer.MAX_VALUE;
                    if (split_.length >= 3) {
                        num_ = split_[2];
                        number_ = Integer.parseInt(num_);
                    }
                    if (split.length >= 3) {
                        num = split[2];
                        number = Integer.parseInt(num);
                    }
                    if (number > number_) {
                        OrderVOMax t = res.get(j);
                        OrderVOMax t_ = res.get(j + 1);
                        res.set(j, t_);
                        res.set(j + 1, t);
                    }

                }
            }
        }


        List<Map<String, Map<String, Map<String, Integer>>>> detail = new ArrayList<>();
        if (areas != null) {

            for (String a : areas) {


                Map<String, Integer> one1 = new LinkedHashMap<>();

                one1.put("counts", 0);

                one1.put("totals", 0);

                Map<String, Integer> one2 = new LinkedHashMap<>();

                one2.put("counts", 0);

                one2.put("totals", 0);

                Map<String, Integer> one3 = new LinkedHashMap<>();

                one3.put("counts", 0);

                one3.put("totals", 0);

                Map<String, Integer> one4 = new LinkedHashMap<>();

                one4.put("counts", 0);

                one4.put("totals", 0);

                Map<String, Integer> one5 = new LinkedHashMap<>();

                one5.put("counts", 0);

                one5.put("totals", 0);

                Map<String, Integer> one6 = new LinkedHashMap<>();

                one6.put("counts", 0);

                one6.put("totals", 0);

                Map<String, Integer> one7 = new LinkedHashMap<>();

                one7.put("counts", 0);

                one7.put("totals", 0);

                Map<String, Map<String, Integer>> two = new LinkedHashMap<>();

                two.put("楼下", one1);
                two.put("一层", one2);
                two.put("二层", one3);
                two.put("三层", one4);
                two.put("四层", one5);
                two.put("五层", one6);
                two.put("六层", one7);

                Map<String, Map<String, Map<String, Integer>>> three = new LinkedHashMap<>();

                three.put(a, two);

                HistoryOrderVO.Build build = new HistoryOrderVO.Build();

                Integer counts = 0;
                Integer totals = 0;

                for (OrderVOMax r : res) {
                    String address = r.getAddress();
                    String[] split = address.split("/");
                    String s = split[0];

                    if (a.equals(s)) {
                        List<OrderCount> orderCounts = r.getOrderCounts();
                        Integer orderStatus = r.getOrderStatus();
//                                            String address_ = r.getAddress();
//                                            String[] split_ = address_.split("/");

                        String s1 = split[1];
                        switch (s1) {
                            case "楼下": {
                                Map<String, Integer> lx = three.get(a).get("楼下");
                                lx.put("totals", lx.get("totals") + 1);
                                if (orderStatus == 3) {
                                    lx.put("counts", lx.get("counts") + 1);
                                }
                                break;
                            }
                            case "一层": {
                                Map<String, Integer> lx = three.get(a).get("一层");
                                lx.put("totals", lx.get("totals") + 1);
                                if (orderStatus == 3) {
                                    lx.put("counts", lx.get("counts") + 1);
                                }
                                break;
                            }
                            case "二层": {
                                Map<String, Integer> lx = three.get(a).get("二层");
                                lx.put("totals", lx.get("totals") + 1);
                                if (orderStatus == 3) {
                                    lx.put("counts", lx.get("counts") + 1);
                                }
                                break;
                            }
                            case "三层": {
                                Map<String, Integer> lx = three.get(a).get("三层");
                                lx.put("totals", lx.get("totals") + 1);
                                if (orderStatus == 3) {
                                    lx.put("counts", lx.get("counts") + 1);
                                }
                                break;
                            }
                            case "四层": {
                                Map<String, Integer> lx = three.get(a).get("四层");
                                lx.put("totals", lx.get("totals") + 1);
                                if (orderStatus == 3) {
                                    lx.put("counts", lx.get("counts") + 1);
                                }
                                break;
                            }
                            case "五层": {
                                Map<String, Integer> lx = three.get(a).get("五层");
                                lx.put("totals", lx.get("totals") + 1);
                                if (orderStatus == 3) {
                                    lx.put("counts", lx.get("counts") + 1);
                                }
                                break;
                            }
                            case "六层": {
                                Map<String, Integer> lx = three.get(a).get("六层");
                                lx.put("totals", lx.get("totals") + 1);
                                if (orderStatus == 3) {
                                    lx.put("counts", lx.get("counts") + 1);
                                }
                                break;
                            }
                        }
                        if (orderStatus != -3) {
                            totals++;
                        }
                        if (orderStatus == 3) {
                            counts++;
                        }


                    }
                    String substring = a.substring(2, a.length());
                    build.setBuild(substring);

                }
                detail.add(three);
                build.setCounts(counts);
                build.setTotals(totals);
                builds.add(build);

            }
        }

        historyOrderVO.setDetail(detail);

        /**
         *
         * 统计有效订单数量
         *
         */
        for (OrderVOMax orderVOMax : orderVOMaxes) {
            Long id1 = orderVOMax.getId();
            List<OrderCount> orderCounts = orderCountMapper.selectEffective(id1);
            if (orderCounts == null || orderCounts.size() == 0) {
                orderVOMax.setEffectiveCount(0);
            } else {
                orderVOMax.setEffectiveCount(orderCounts.size());
            }
        }


        historyOrderVO.setBuilds(builds);


        for (String a : areas) {

//            HistoryOrderVO.Build build = new HistoryOrderVO.Build();
            Integer counts = 0;
            Integer totals = 0;

            for (OrderVOMax r : res) {
                String address = r.getAddress();
                String[] split = address.split("/");
                String s = split[0];

                if (a.equals(s)) {
                    List<OrderCount> orderCounts = r.getOrderCounts();
                    Integer orderStatus = r.getOrderStatus();

                    if (orderCounts == null || orderCounts.size() == 1 || orderCounts == null) {
                        if (orderStatus != -3) {
                            totals++;
                            if (orderStatus == 3) {
                                counts++;
                            }
                        }
                    }
                }
//                String substring = a.substring(2, a.length());
//                build.setBuild(substring);
            }
//            build.setCounts(counts);
//            build.setTotals(totals);
//            builds.add(build);
        }

    }

    private void values1(HistoryOrderVO historyOrderVO, List<OrderVOMax> res, Integer id) {

        long start6 = start();

        //查询地区
        List<String> areas = new ArrayList<>();
        historyOrderVO.setAreas(areas);
        areas = manageBookMapper.selectInfo(id);

        long end6 = end();
        System.out.println("查询地区" + (end6 - start6));

        long start7 = start();

        historyOrderVO.setBuildsType(0);

        if (areas.size() != 28) {
            historyOrderVO.setBuildsType(1);
        } else {
            areas.stream().forEach(s -> {
                String substring = s.substring(0, 2);
                if (!substring.equals("静园")) {
                    historyOrderVO.setBuildsType(1);
                }
            });
        }


        if (areas != null) {
            areas.sort(Comparator.comparingInt(a -> Integer.parseInt(getNum(a))));

//            for (int i = 0; i < areas.size() - 1; i++) {
//                for (int j = 0; j < areas.size() - i - 1; j++) {
//                    String s = areas.get(j);
//                    String w = areas.get(j + 1);
//                    String num1 = getNum(s);
//                    String num2 = getNum(w);
//                    Integer x = Integer.parseInt(num1);
//                    Integer y = Integer.parseInt(num2);
//                    if (x > y) {
//                        String s1 = areas.get(j);
//                        String s2 = areas.get(j + 1);
//                        areas.set(j, s2);
//                        areas.set(j + 1, s1);
//                    }
//                }
//            }

            historyOrderVO.setAreas(areas);
        }
        long end7 = end();
        System.out.println("地区排序:" + (end7 - start7));

        //查询所有已接的订单
        long start8 = start();

        List<OrderVOMax> orderVOMaxes = selectAllOrders1();
        List<HistoryOrderVO.Build> builds = new ArrayList<>();
        long end8 = end();
        System.out.println("查询已接订单" + (end8 - start8));
        long start3 = start();

        //按区域分配
        if (orderVOMaxes != null) {
            for (OrderVOMax orderVOMax : orderVOMaxes) {
                String address = orderVOMax.getAddress();
                String[] split = address.split("/");
                String addr = split[0];
                for (String area : areas) {
                    if (addr.equals(area)) {
                        res.add(orderVOMax);
                        break;
                    }
                }
            }
        }

        long end3 = end();
        System.out.println("区域分配订单:" + (end3 - start3));

        long start4 = start();
        List<Map<String, Map<String, Map<String, Integer>>>> detail = new ArrayList<>();

        if (areas != null) {

            for (String a : areas) {

                Map<String, Integer> one1 = new LinkedHashMap<>();

                one1.put("counts", 0);

                one1.put("totals", 0);

                Map<String, Integer> one2 = new LinkedHashMap<>();

                one2.put("counts", 0);

                one2.put("totals", 0);

                Map<String, Integer> one3 = new LinkedHashMap<>();

                one3.put("counts", 0);

                one3.put("totals", 0);

                Map<String, Integer> one4 = new LinkedHashMap<>();

                one4.put("counts", 0);

                one4.put("totals", 0);

                Map<String, Integer> one5 = new LinkedHashMap<>();

                one5.put("counts", 0);

                one5.put("totals", 0);

                Map<String, Integer> one6 = new LinkedHashMap<>();

                one6.put("counts", 0);

                one6.put("totals", 0);

                Map<String, Integer> one7 = new LinkedHashMap<>();

                one7.put("counts", 0);

                one7.put("totals", 0);

                Map<String, Map<String, Integer>> two = new LinkedHashMap<>();

                two.put("楼下", one1);
                two.put("一层", one2);
                two.put("二层", one3);
                two.put("三层", one4);
                two.put("四层", one5);
                two.put("五层", one6);
                two.put("六层", one7);

                Map<String, Map<String, Map<String, Integer>>> three = new LinkedHashMap<>();

                three.put(a, two);

                HistoryOrderVO.Build build = new HistoryOrderVO.Build();
                String substring = a.substring(2, a.length());
                build.setBuild(substring);
                Integer counts = 0;
                Integer totals = 0;

                for (OrderVOMax r : res) {
                    String address = r.getAddress();
                    String[] split = address.split("/");
                    String s = split[0];

                    if (a.equals(s)) {
                        List<OrderCount> orderCounts = r.getOrderCounts();
                        Integer orderStatus = r.getOrderStatus();
//                                            String address_ = r.getAddress();
//                                            String[] split_ = address_.split("/");

                        if (orderCounts == null || orderCounts.size() == 1) {
                            String s1 = split[1];
                            switch (s1) {
                                case "楼下": {
                                    Map<String, Integer> lx = three.get(a).get("楼下");
                                    if (orderStatus != -3) {
                                        lx.put("totals", lx.get("totals") + 1);
                                    }
                                    if (orderStatus == 3) {
                                        lx.put("counts", lx.get("counts") + 1);
                                    }
                                    break;
                                }
                                case "一层": {
                                    Map<String, Integer> lx = three.get(a).get("一层");
                                    if (orderStatus != -3) {
                                        lx.put("totals", lx.get("totals") + 1);
                                    }
                                    if (orderStatus == 3) {
                                        lx.put("counts", lx.get("counts") + 1);
                                    }
                                    break;
                                }
                                case "二层": {
                                    Map<String, Integer> lx = three.get(a).get("二层");
                                    if (orderStatus != -3) {
                                        lx.put("totals", lx.get("totals") + 1);
                                    }
                                    if (orderStatus == 3) {
                                        lx.put("counts", lx.get("counts") + 1);
                                    }
                                    break;
                                }
                                case "三层": {
                                    Map<String, Integer> lx = three.get(a).get("三层");
                                    if (orderStatus != -3) {
                                        lx.put("totals", lx.get("totals") + 1);
                                    }
                                    if (orderStatus == 3) {
                                        lx.put("counts", lx.get("counts") + 1);
                                    }
                                    break;
                                }
                                case "四层": {
                                    Map<String, Integer> lx = three.get(a).get("四层");
                                    if (orderStatus != -3) {
                                        lx.put("totals", lx.get("totals") + 1);
                                    }
                                    if (orderStatus == 3) {
                                        lx.put("counts", lx.get("counts") + 1);
                                    }
                                    break;
                                }
                                case "五层": {
                                    Map<String, Integer> lx = three.get(a).get("五层");
                                    if (orderStatus != -3) {
                                        lx.put("totals", lx.get("totals") + 1);
                                    }
                                    if (orderStatus == 3) {
                                        lx.put("counts", lx.get("counts") + 1);
                                    }
                                    break;
                                }
                                case "六层": {
                                    Map<String, Integer> lx = three.get(a).get("六层");
                                    if (orderStatus != -3) {
                                        lx.put("totals", lx.get("totals") + 1);
                                    }
                                    if (orderStatus == 3) {
                                        lx.put("counts", lx.get("counts") + 1);
                                    }
                                    break;
                                }
                            }
                            if (orderStatus != -3) {
                                totals++;
                            }
                            if (orderStatus == 3) {
                                counts++;
                            }

                        }
                    }
                }
                detail.add(three);
                build.setCounts(counts);
                build.setTotals(totals);
                builds.add(build);

            }
        }

        historyOrderVO.setDetail(detail);
        historyOrderVO.setBuilds(builds);
        long end4 = end();
        System.out.println("统计各楼件（各层）数：" + (end4 - start4));
//        for (int i = 0; i < res.size() - 1; i++) {
//            for (int j = 0; j < res.size() - i - 1; j++) {
//                OrderVOMax orderVOMax = res.get(j);
//                OrderVOMax orderVOMax_ = res.get(j + 1);
//                String address = orderVOMax.getAddress();
//                String address_ = orderVOMax_.getAddress();
//                String[] split = address.split("/");
//                String[] split_ = address_.split("/");
//                String num;
//                String num_;
//                int number = Integer.MAX_VALUE;
//                int number_ = Integer.MAX_VALUE;
//                if (split_.length >= 3) {
//                    num_ = split_[2];
//                    number_ = Integer.parseInt(num_);
//                }
//                if (split.length >= 3) {
//                    num = split[2];
//                    number = Integer.parseInt(num);
//                }
//                if (number > number_) {
//                    OrderVOMax t = res.get(j);
//                    OrderVOMax t_ = res.get(j + 1);
//                    res.set(j, t_);
//                    res.set(j + 1, t);
//                }
//            }
//        }


//        List<OrderVOMax> l = new ArrayList<>();
        long start5 = start();


        List<OrderVOMax> l = res.stream().filter(orderVOMax -> orderVOMax.getOrderCounts() != null).filter(orderVOMax -> orderVOMax.getOrderCounts().size() > 1).collect(Collectors.toList());

        long end5 = end();
        System.out.println("过滤多件订单：" + (end5 - start5));
        //        for (OrderVOMax re : res) {
//            List<OrderCount> orderCounts = re.getOrderCounts();
//            if (orderCounts == null) {
//                continue;
//            }
//            if (re.getOrderStatus() == -2 || orderCounts.size() > 1) {
//                l.add(re);
//            }
//            if (re.getOrderStatus() == -3) {
//                if (re.getOrderCounts().size() > 1) {
//                    l.add(re);
//                }
//            }
//        }
        long start = start();


        Map<String, Map<String, Integer>> category = new LinkedHashMap<>();

        LinkedHashMap<String, Integer> value1 = new LinkedHashMap<>();
        value1.put("total", 0);
        value1.put("collected", 0);
        value1.put("available", 0);
        LinkedHashMap<String, Integer> value2 = new LinkedHashMap<>();
        value2.put("total", 0);
        value2.put("collected", 0);
        value2.put("available", 0);
        LinkedHashMap<String, Integer> value3 = new LinkedHashMap<>();
        value3.put("total", 0);
        value3.put("collected", 0);
        value3.put("available", 0);
        LinkedHashMap<String, Integer> value4 = new LinkedHashMap<>();
        value4.put("total", 0);
        value4.put("collected", 0);
        value4.put("available", 0);
        LinkedHashMap<String, Integer> value5 = new LinkedHashMap<>();
        value5.put("total", 0);
        value5.put("collected", 0);
        value5.put("available", 0);

        category.put("yd8", value1);
        category.put("other", value2);
        category.put("s3d41", value3);
        category.put("s2d38", value4);
        category.put("cabinet", value5);


        //TODO 排序
        //分类各种件数
        List<OrderVOMax>[] big = new List[3];
        for (int i = 0; i < big.length; i++) {
            big[i] = new ArrayList<>();
        }
        for (int i = 0; i < res.size(); i++) {
            OrderVOMax orderVOMax = res.get(i);
            Integer x = 0;
            List<OrderCount> orderCounts1 = orderVOMax.getOrderCounts();
            if (orderCounts1 != null) {
                x = orderCounts1.size();
            }
            if (orderVOMax.getOrderStatus() != -2 && x == 1) {
                List<OrderCount> orderCounts = orderVOMax.getOrderCounts();
                if (orderCounts != null && orderCounts.size() != 0) {
                    OrderCount orderCount = orderCounts.get(0);
                    String takeCode = orderCount.getTakeCode();
                    if (RegularExpression.kf(takeCode)) {
                        category.compute("other", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus = orderVOMax.getOrderStatus();
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus == 25 || orderStatus == -25) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("collected") + 1);
                                }

                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                        big[0].add(orderVOMax);
                    } else if (RegularExpression.yd8(takeCode) || RegularExpression.sf(takeCode) || RegularExpression.pdd(takeCode) || RegularExpression.jd(takeCode)) {
                        category.compute("yd8", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus = orderVOMax.getOrderStatus();
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus == 21 || orderStatus == -21) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                        big[0].add(orderVOMax);
                    } else if (RegularExpression.s3d41(takeCode)) {
                        category.compute("s3d41", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus = orderVOMax.getOrderStatus();
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }

                                if (orderStatus == 22 || orderStatus == -22) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                        big[0].add(orderVOMax);
                    } else if (RegularExpression.s2d38(takeCode)) {
                        category.compute("s2d38", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus = orderVOMax.getOrderStatus();
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus == 23 || orderStatus == -23) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                        big[0].add(orderVOMax);
                    } else if (RegularExpression.cabinet(takeCode)) {
                        category.compute("cabinet", new BiFunction<String, Map<String, Integer>, Map<String, Integer>>() {

                            public Map<String, Integer> apply(String s, Map<String, Integer> stringIntegerMap) {
                                Integer orderStatus = orderVOMax.getOrderStatus();
                                if (stringIntegerMap == null) {
                                    stringIntegerMap = new LinkedHashMap<>();
                                    stringIntegerMap.put("total", 0);
                                    stringIntegerMap.put("collected", 0);
                                    stringIntegerMap.put("available", 0);
                                }
                                if (orderStatus == 3) {
                                    stringIntegerMap.put("collected", stringIntegerMap.get("collected") + 1);
                                }
                                if (orderStatus == 24 || orderStatus == -24) {
                                    stringIntegerMap.put("available", stringIntegerMap.get("available") + 1);
                                }
                                stringIntegerMap.put("total", stringIntegerMap.get("collected") + stringIntegerMap.get("available"));
                                return stringIntegerMap;
                            }
                        });
                        big[2].add(orderVOMax);
                    }
                }
            }
        }
        historyOrderVO.setCategory(category);
        res.clear();
        if (big[0] != null && big[0].size() != 0) {
            List<OrderVOMax>[] mid = new List[110];
            for (int i = 0; i < mid.length; i++) {
                mid[i] = new ArrayList();
            }
            List<OrderVOMax> other = new ArrayList<>();
            Pattern p = Pattern.compile("A...");
            Pattern p_ = Pattern.compile("88");
            Pattern p__ = Pattern.compile("J");
            Pattern p___ = Pattern.compile("50");
            Pattern p____ = Pattern.compile("kf");
            for (OrderVOMax orderVOMax : big[0]) {
                String takeCode = getCode(orderVOMax);
                String[] one_ = takeCode.split("-");
                Matcher m = p.matcher(one_[0]);
                Matcher m_ = p_.matcher(one_[0]);
                Matcher m__ = p__.matcher(one_[0]);
                Matcher m___ = p___.matcher(one_[0]);
                Matcher m____ = p____.matcher(one_[0]);
                if (m.matches() || m_.matches() || m__.matches() || m___.matches() || m____.matches()) {
                    other.add(orderVOMax);
                    continue;
                }
                int one = Integer.parseInt(one_[0]);
                mid[one].add(orderVOMax);
            }

            for (List<OrderVOMax> list : mid) {

                list.sort(Comparator.comparingInt(o -> Integer.parseInt(getCode(o).split("-")[1])));
//                for (int i = 0; i < list.size() - 1; i++) {
//                    for (int j = 0; j < list.size() - 1 - i; j++) {
//                        OrderVOMax orderVOMax1 = list.get(j);
//                        OrderVOMax orderVOMax2 = list.get(j + 1);
//                        String code1 = getCode(orderVOMax1);
//                        String[] split1 = code1.split("-");
//                        String s1 = split1[1];
//                        int o1 = Integer.parseInt(s1);
//                        String code2 = getCode(orderVOMax2);
//                        String[] split2 = code2.split("-");
//                        String s2 = split2[1];
//                        int o2 = Integer.parseInt(s2);
//                        if (o1 > o2) {
//                            list.set(j, orderVOMax2);
//                            list.set(j + 1, orderVOMax1);
//                        }
//                    }
//                }
            }


            //1-50的桶里面已经排好序  32, 28, 24, 20, 16, 12, 14, 18, 22, 26, 30, 34, 36, 38
            int[] rule = {1, 2, 3, 4, 5, 6, 7, 8, 15, 13, 17, 19, 41, 21, 23, 39, 25, 27, 37, 29, 31, 35, 33, 12, 14, 16, 18, 20, 22, 26, 24, 30, 28, 34, 32, 36, 38};

//            for (int i = 0; i < mid.length; i++) {
//                if(mid[i].size()>0){
//                    System.out.println(i+" "+mid[i].size());
//                }
//            }


            for (int i : rule) {
                if (mid[i] != null && mid[i].size() != 0) {
//                    System.out.println(i+" "+mid[i].size());
                    res.addAll(mid[i]);
                }
            }


            //排好操作
//            for (List<OrderVOMax> list : mid) {
//                if (list != null && list.size() != 0) {
//                    res.addAll(list);
//                }
//            }
            if (other != null && other.size() != 0) {
                res.addAll(other);
            }
        }

        //72-74排序取消
//        if (big[1] != null && big[1].size() != 0) {
//            List<OrderVOMax>[] mid = new List[100];
//            for (int i = 0; i < mid.length; i++) {
//                mid[i] = new ArrayList();
//            }
//            for (OrderVOMax orderVOMax : big[1]) {
//                String takeCode = getCode(orderVOMax);
//                String[] one_ = takeCode.split("-");
//                int one = Integer.parseInt(one_[0]);
//                mid[one].add(orderVOMax);
//            }
//            for (List<OrderVOMax> list : mid) {
//                for (int i = 0; i < list.size() - 1; i++) {
//                    for (int j = 0; j < list.size() - 1 - i; j++) {
//                        OrderVOMax orderVOMax1 = list.get(j);
//                        OrderVOMax orderVOMax2 = list.get(j + 1);
//                        String code1 = getCode(orderVOMax1);
//                        String[] split1 = code1.split("-");
//                        String s1 = split1[1];
//                        int o1 = Integer.parseInt(s1);
//                        String code2 = getCode(orderVOMax2);
//                        String[] split2 = code2.split("-");
//                        String s2 = split2[1];
//                        int o2 = Integer.parseInt(s2);
//                        if (o1 > o2) {
//                            list.set(j, orderVOMax2);
//                            list.set(j + 1, orderVOMax1);
//                        }
//                    }
//                }
//            }
//            //排好操作
//            for (List<OrderVOMax> list : mid) {
//                if (list != null && list.size() != 0) {
//                    res.addAll(list);
//                }
//            }
//        }

        if (big[2] != null && big[2].size() != 0) {
            List<OrderVOMax>[] mid = new List[15];
            for (int i = 0; i < mid.length; i++) {
                mid[i] = new ArrayList();
            }
            List<OrderVOMax> other = new ArrayList<>();
//            Pattern p = Pattern.compile("88");
            for (OrderVOMax orderVOMax : big[2]) {
                String takeCode = getCode(orderVOMax);
                String[] one_ = takeCode.split("-");
//                System.out.println(one_[0]);
//                Matcher m = p.matcher(one_[0]);
//                if (m.matches()) {
//                    other.add(orderVOMax);
//                    continue;
//                }
                int one = Integer.parseInt(one_[0]);
                mid[one].add(orderVOMax);
            }
            //排好操作
            for (List<OrderVOMax> list : mid) {
                if (list != null && list.size() != 0) {
                    res.addAll(list);
                }
            }
//            if (other != null && other.size() != 0) {
//                for (int i = 0; i < other.size() - 1; i++) {
//                    for (int j = 0; j < other.size() - 1 - i; j++) {
//                        OrderVOMax orderVOMax1 = other.get(j);
//                        OrderVOMax orderVOMax2 = other.get(j + 1);
//                        String code1 = getCode(orderVOMax1);
//                        String[] split1 = code1.split("-");
//                        String s1 = split1[1];
//                        int o1 = Integer.parseInt(s1);
//                        String code2 = getCode(orderVOMax2);
//                        String[] split2 = code2.split("-");
//                        String s2 = split2[1];
//                        int o2 = Integer.parseInt(s2);
//                        if (o1 > o2) {
//                            other.set(j, orderVOMax2);
//                            other.set(j + 1, orderVOMax1);
//                        }
//                    }
//
//                }
//
//                res.addAll(other);
//            }
        }

        res.addAll(l);
        long end = end();
        System.out.println("排序耗时：" + (end - start));
    }

    private static String getCode(OrderVOMax orderVOMax) {
        List<OrderCount> orderCounts = orderVOMax.getOrderCounts();
        OrderCount orderCount = orderCounts.get(0);
        String takeCode = orderCount.getTakeCode();
        return takeCode;
    }

    public List<OrderVOMax> selectAllOrders() {

        //获取openid
        String openid = "oD1dE6RdILU9O-EXNaaOSc4cK2-g";

        long start = start();

        //接单结果集合
        List<OrderVOMax> takeRes = new ArrayList<>();

        long start10 = start();
        List<Long> numberList = takeOrderMapper.selectTakes_(openid);

        long end10 = end();
        System.out.println("number" + (end10 - start10));

        if (numberList == null || numberList.size() == 0) {
            return null;
        }

        List<Order> order = orderMapper.selectByNumber_(numberList);

        order.stream().forEach(new Consumer<Order>() {
            public void accept(Order order) {

                String imgs = order.getImgs();
                if (imgs != null) {
                    String[] str = imgs.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        str[i] = serverPath + str[i];
                    }
                    //图片
                    List<String> images = Arrays.asList(str);
                    order.setImages(images);
                } else {
                    order.setImages(null);
                }
                if (order.getImageOver() != null) {
                    order.setImageOver(serverPath + order.getImageOver());
                } else {
                    order.setImageOver(null);
                }
                List<OrderCount> orderCounts = orderCountMapper.selectCodes(order.getId());
                order.setOrderCounts(orderCounts);
            }
        });

        for (Order order1 : order) {
            OrderVOMax o = new OrderVOMax();
            o.setId(order1.getId());
            o.setNumber(order1.getNumber());
            o.setOrderStatus(order1.getOrderStatus());
            o.setImageOver(order1.getImageOver());
            o.setCount(order1.getCount());
            o.setRemark(order1.getRemark());
            o.setPhone(order1.getPhone());
            o.setPackageInfo(order1.getPackageInfo());
            o.setAddress(order1.getAddress());
            o.setImages(order1.getImages());
            o.setOrderCounts(order1.getOrderCounts());
            o.setOrderType(order1.getOrderType());
            takeRes.add(o);
        }

        return takeRes;
    }

    @Transactional
    public synchronized List<OrderVOMax> selectAllOrders1() {

        //获取openid
        String openid = "oD1dE6RdILU9O-EXNaaOSc4cK2-g";
        long start = start();
        //接单结果集合
        List<OrderVOMax> takeRes = new ArrayList<>();

        long start10 = start();
        List<Long> numberList = takeOrderMapper.selectTakes(openid);
        long end10 = end();
        System.out.println("number" + (end10 - start10));

        if (numberList == null || numberList.size() == 0) {
            return null;
        }

        List<Order> order = orderMapper.selectByNumber_(numberList);

        order.stream().forEach(new Consumer<Order>() {
            public void accept(Order order) {

                String imgs = order.getImgs();
                if (imgs != null) {
                    String[] str = imgs.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        str[i] = serverPath + str[i];
                    }
                    //图片
                    List<String> images = Arrays.asList(str);
                    order.setImages(images);
                } else {
                    order.setImages(null);
                }
                if (order.getImageOver() != null) {
                    order.setImageOver(serverPath + order.getImageOver());
                } else {
                    order.setImageOver(null);
                }
                List<OrderCount> orderCounts = orderCountMapper.selectCodes(order.getId());
                order.setOrderCounts(orderCounts);
            }
        });


//        order.stream().forEach(order1 -> System.out.println(order1.getOrderCounts()));

//        System.out.println(order.size());
//        for (Long number : numberList) {
//
//            Order order = orderMapper.selectByNumber(number);
//            String imgs = order.getImgs();
//            if(imgs!=null){
//                String[] str = imgs.split(" ");
//                for (int i = 0; i < str.length; i++) {
//                    str[i] = serverPath + str[i];
//                }
//                //图片
//                List<String> images = Arrays.asList(str);
//                order.setImages(images);
//            }else {
//                order.setImages(null);
//            }
//            //取件码
//            List<OrderCount> orderCounts = orderCountMapper.selectCodes(order.getId());
//            order.setOrderCounts(orderCounts);
//
//            orders.add(order);
//        }
//        BeanUtils.copyProperties(orders,takeRes);
        long end = end();
        System.out.println("接单列表基本信息" + (end - start));
//        System.out.println(orders.size());

        //搞接单列表基本信息
//        List<TakeOrders> orderList = takeOrderMapper.selectPathTakes2(openid);
//        List<TakeOrders> orderList2 = takeOrderMapper.selectPathTakes2(openid);
//        orderList.addAll(orderList2);
//        //搞每个订单的订单详细信息
//        long start9 = start();
//
//        //遍历接单结果
//        for (int i = 0; i < orderList.size(); i++) {
//
//            //创建返回结果对象
//            OrderVOMax orderVO = new OrderVOMax();
//
//            //获得接单
//            TakeOrders takeOrder = orderList.get(i);
//
//            //获得订单号
//            Long number = takeOrder.getNumber();
//
//            //根据接单号查询 搞好订单详细信息
//            List<Orders> takeList = orderMapper.selectTakes(number);
//
//
//            /**
//             * 取件码代码段
//             */
//            //查询取件码
//            Orders orders1 = takeList.get(0);
//            Long id = orders1.getId();
//            //寻找取件码信息
//            List<OrderCount> orderCounts = orderCountMapper.selectByOrderId(Math.toIntExact(id));
//            if (orderCounts == null || orderCounts.size() == 0) {
//                orderVO.setOrderCounts(null);
//            } else {
//                orderVO.setOrderCounts(orderCounts);
//            }
//
//
//            /**
//             * 送达完成图片
//             */
//            for (Orders orders : takeList) {
//                String imageOver = orders.getImageOver();
//                if (imageOver != null && imageOver != "") {
////                    System.out.println(imageOver);
//                    orders.setImageOver(serverPath + imageOver);
//                }
//            }
//
//
//            //创建图片列表
//            List<String> imgList = new ArrayList<>();
//
//
//            //先把订单详细信息确认 只需拷贝一次
//            if (!takeList.isEmpty()) {
//                BeanUtils.copyProperties(takeList.get(0), orderVO, new String[]{"image"});
//                String image = takeList.get(0).getImage();
//                if (image != null) {
//                    image = serverPath + image;
//                    imgList.add(image);
//                }
//                //移除
//                takeList.remove(0);
//            }
//
//            //遍历订单 搞图片
//            for (int j = 0; j < takeList.size(); ) {
//                //获取一个订单信息
//                Orders order = takeList.get(j);
//                //获取图片信息
//                String image = order.getImage();
//                if (image != null) {
//                    image = serverPath + image;
//                    //添加到图片列表里
//                    imgList.add(image);
//                }
//
//                //移除
//                Orders remove = takeList.remove(j);
//                //没有移除
//                if (remove == null) {
//                    j++;
//                }
//            }
//            if (imgList != null) {
//                orderVO.setImages(imgList);
//            }
//
//            //搞接单人信息
//            //接单信息
//            if (takeOrder != null) {
//                orderVO.setTakeoutTime(takeOrder.getTakeorderTime());
//                orderVO.setTakeTime(takeOrder.getTakeTime());
//                orderVO.setDeliveryTime(takeOrder.getDeliveryTime());
//            }
//
//            //寻找接单人信息
//            String openid_ = null;
//            //寻找接单人信息
//            if (takeOrder != null) {
//                openid_ = takeOrder.getOpenid();
//            }
//            AddressBook addressBook = userMapper.selectByOpenidMax(openid_);
//            if (addressBook != null) {
//                orderVO.setHelperPhone(addressBook.getPhone());
//                orderVO.setHelperAddress(addressBook.getAddress());
//            }
//            orderVO.setOrderType(takeOrder.getOrderType());
//            takeRes.add(orderVO);
//        }
//        long end9 = end();
//        System.out.println("接单列表基本信息lll"+(end9-start9));

        List<OrderVOMax> res = new ArrayList<>();
        long start2 = start();
        for (Order take : order) {
            Integer status = take.getOrderStatus();
            Long id = take.getId();
//            List<OrderCount> orderCounts = orderCountMapper.selectByOrderId(Math.toIntExact(id));
            List<OrderCount> orderCounts = take.getOrderCounts();
            if ((status == 3 && orderCounts.size() > 1) || status == 6 || status == -2 || (status == -3 && orderCounts.size() > 1)) {

                if (orderCounts != null && orderCounts.size() > 1) {
//                    List<OrderCount> ins = new ArrayList<>();
//                    List<OrderCount> outs = new ArrayList<>();
//                    List<OrderCount> cabinet = new ArrayList<>();

                    for (OrderCount count : orderCounts) {
                        String takeCode = count.getTakeCode();
                        if (RegularExpression.yd8(takeCode) || RegularExpression.sf(takeCode) || RegularExpression.pdd(takeCode) || RegularExpression.jd(takeCode)) {
                            long l = (count.getId() - 2 * count.getId()) * 100;
                            Fake fake1 = fakeMapper.selectById(l);
                            if (fake1 == null) {
                                Fake fake = new Fake();
                                fake.setId(l);
                                fake.setOrderStatus(-21);
                                fake.setOrderId(Math.toIntExact(id));
                                fake.setCountId(count.getId());
                                fakeMapper.insert(fake);
                                Integer fakeId = fake.getFakeId();
                                Fake fake2 = fakeMapper.selectByFakeId(fakeId);
                                List<OrderCount> ins = new ArrayList<>();
                                OrderVOMax om = new OrderVOMax();
                                BeanUtils.copyProperties(take, om);
                                om.setId(fake2.getId());
                                om.setOrderStatus(fake2.getOrderStatus());
                                ins.add(count);
                                om.setOrderCounts(ins);
                                res.add(om);
                            } else {
//                                List<Fake> fakes = fakeMapper.selectByOrderId(id);
//                                fakeMapper.updateState(fake.getFakeId());
                                Fake fake = fakeMapper.selectById(l);
                                if (fake.getOrderStatus() != -3) {
                                    List<OrderCount> ins = new ArrayList<>();
                                    OrderVOMax om = new OrderVOMax();
                                    BeanUtils.copyProperties(take, om);
                                    om.setId(fake.getId());
                                    om.setOrderStatus(fake.getOrderStatus());
                                    ins.add(count);
                                    om.setOrderCounts(ins);
                                    res.add(om);
                                }

                            }
                        } else if (RegularExpression.s3d41(takeCode)) {
                            long l = (count.getId() - 2 * count.getId()) * 100 - 1;
                            Fake fake1 = fakeMapper.selectById(l);
                            if (fake1 == null) {
                                Fake fake = new Fake();
                                fake.setId(l);
                                fake.setOrderStatus(-22);
                                fake.setOrderId(Math.toIntExact(id));
                                fake.setCountId(count.getId());
                                fakeMapper.insert(fake);
                                Integer fakeId = fake.getFakeId();
                                Fake fake2 = fakeMapper.selectByFakeId(fakeId);
                                List<OrderCount> ins = new ArrayList<>();
                                OrderVOMax om = new OrderVOMax();
                                BeanUtils.copyProperties(take, om);
                                om.setId(fake2.getId());
                                om.setOrderStatus(fake2.getOrderStatus());
                                ins.add(count);
                                om.setOrderCounts(ins);
                                res.add(om);
                            } else {
                                Fake fake = fakeMapper.selectById(l);
                                if (fake.getOrderStatus() != -3) {
                                    List<OrderCount> ins = new ArrayList<>();
                                    OrderVOMax om = new OrderVOMax();
                                    BeanUtils.copyProperties(take, om);
                                    om.setId(fake.getId());
                                    om.setOrderStatus(fake.getOrderStatus());
                                    ins.add(count);
                                    om.setOrderCounts(ins);
                                    res.add(om);
                                }
                            }
                        } else if (RegularExpression.s2d38(takeCode)) {
                            long l = (count.getId() - 2 * count.getId()) * 100 - 2;
                            Fake fake1 = fakeMapper.selectById(l);
                            if (fake1 == null) {
                                Fake fake = new Fake();
                                fake.setId(l);
                                fake.setOrderStatus(-23);
                                fake.setOrderId(Math.toIntExact(id));
                                fake.setCountId(count.getId());
                                fakeMapper.insert(fake);
                                Integer fakeId = fake.getFakeId();
                                Fake fake2 = fakeMapper.selectByFakeId(fakeId);
                                List<OrderCount> ins = new ArrayList<>();
                                OrderVOMax om = new OrderVOMax();
                                BeanUtils.copyProperties(take, om);
                                om.setId(fake2.getId());
                                om.setOrderStatus(fake2.getOrderStatus());
                                ins.add(count);
                                om.setOrderCounts(ins);
                                res.add(om);
                            } else {
                                Fake fake = fakeMapper.selectById(l);
                                if (fake.getOrderStatus() != -3) {
                                    List<OrderCount> ins = new ArrayList<>();
                                    OrderVOMax om = new OrderVOMax();
                                    BeanUtils.copyProperties(take, om);
                                    om.setId(fake.getId());
                                    om.setOrderStatus(fake.getOrderStatus());
                                    ins.add(count);
                                    om.setOrderCounts(ins);
                                    res.add(om);
                                }
                            }
                        } else if (RegularExpression.kf(takeCode)) {
                            long l = (count.getId() - 2 * count.getId()) * 100 - 2;
                            Fake fake1 = fakeMapper.selectById(l);
                            if (fake1 == null) {
                                Fake fake = new Fake();
                                fake.setId(l);
                                fake.setOrderStatus(-25);
                                fake.setOrderId(Math.toIntExact(id));
                                fake.setCountId(count.getId());
                                fakeMapper.insert(fake);
                                Integer fakeId = fake.getFakeId();
                                Fake fake2 = fakeMapper.selectByFakeId(fakeId);
                                List<OrderCount> ins = new ArrayList<>();
                                OrderVOMax om = new OrderVOMax();
                                BeanUtils.copyProperties(take, om);
                                om.setId(fake2.getId());
                                om.setOrderStatus(fake2.getOrderStatus());
                                ins.add(count);
                                om.setOrderCounts(ins);
                                res.add(om);
                            } else {
                                Fake fake = fakeMapper.selectById(l);
                                if (fake.getOrderStatus() != -3) {
                                    List<OrderCount> ins = new ArrayList<>();
                                    OrderVOMax om = new OrderVOMax();
                                    BeanUtils.copyProperties(take, om);
                                    om.setId(fake.getId());
                                    om.setOrderStatus(fake.getOrderStatus());
                                    ins.add(count);
                                    om.setOrderCounts(ins);
                                    res.add(om);
                                }
                            }
                        } else if (RegularExpression.cabinet(takeCode)) {
                            long l = (count.getId() - 2 * count.getId()) * 100 - 2;
                            Fake fake1 = fakeMapper.selectById(l);
                            if (fake1 == null) {
                                Fake fake = new Fake();
                                fake.setId(l);
                                fake.setOrderStatus(-24);
                                fake.setOrderId(Math.toIntExact(id));
                                fake.setCountId(count.getId());
                                fakeMapper.insert(fake);
                                Integer fakeId = fake.getFakeId();
                                Fake fake2 = fakeMapper.selectByFakeId(fakeId);
                                List<OrderCount> ins = new ArrayList<>();
                                OrderVOMax om = new OrderVOMax();
                                BeanUtils.copyProperties(take, om);
                                om.setId(fake2.getId());
                                om.setOrderStatus(fake2.getOrderStatus());
                                ins.add(count);
                                om.setOrderCounts(ins);
                                res.add(om);
                            } else {
                                Fake fake = fakeMapper.selectById(l);
                                if (fake.getOrderStatus() != -3) {
                                    List<OrderCount> ins = new ArrayList<>();
                                    OrderVOMax om = new OrderVOMax();
                                    BeanUtils.copyProperties(take, om);
                                    om.setId(fake.getId());
                                    om.setOrderStatus(fake.getOrderStatus());
                                    ins.add(count);
                                    om.setOrderCounts(ins);
                                    res.add(om);
                                }
                            }
                        }


                    }

//                    List<Fake> fakes = fakeMapper.selectByOrderId(id);
//                    for (Fake fake : fakes) {
//                        OrderVOMax om = new OrderVOMax();
//                        BeanUtils.copyProperties(take, om);
//                        om.setId(fake.getId());
//                        om.setOrderStatus(fake.getOrderStatus());
//                        List<OrderCount> ins = new ArrayList<>();
//
//                        ins.add()
//                        om.setOrderCounts();
//                    }


                    /**
                     * 建设中
                     */
//                    for (OrderCount count : orderCounts) {
//                        String takeCode = count.getTakeCode();
//                        if (RegularExpression.in(takeCode) || RegularExpression.sf(takeCode)) {
//                            List<OrderCount> ins = new ArrayList<>();
//                            OrderVOMax om = new OrderVOMax();
//                            BeanUtils.copyProperties(take, om);
//                            om.setId(l--);
//                            om.setOrderStatus(-21);
//                            ins.add(count);
//                            om.setOrderCounts(ins);
//                            res.add(om);
//                        }
//                        if (RegularExpression.out(takeCode)) {
//                            List<OrderCount> outs = new ArrayList<>();
//                            OrderVOMax om = new OrderVOMax();
//                            BeanUtils.copyProperties(take, om);
//                            om.setId(l--);
//                            om.setOrderStatus(-22);
//                            outs.add(count);
//                            om.setOrderCounts(outs);
//                            res.add(om);
//                        }
//                        if (RegularExpression.cabinet(takeCode) || RegularExpression.pdd(takeCode)) {
//                            List<OrderCount> cabinet = new ArrayList<>();
//                            OrderVOMax om = new OrderVOMax();
//                            BeanUtils.copyProperties(take, om);
//                            om.setId(l--);
//                            om.setOrderStatus(-23);
//                            cabinet.add(count);
//                            om.setOrderCounts(cabinet);
//                            res.add(om);
//                        }
//                    }
//
//                    if (ins.size() != 0) {
//                        OrderVOMax om = new OrderVOMax();
//                        BeanUtils.copyProperties(take, om);
//                        om.setId(id - 2 * id);
//                        om.setOrderStatus(-21);
//                        om.setOrderCounts(ins);
//                        res.add(om);
//                    }

//                    if (outs.size() != 0) {
//                        OrderVOMax om = new OrderVOMax();
//                        BeanUtils.copyProperties(take, om);
//                        om.setId(id - 2 * id - 1);
//                        om.setOrderStatus(-22);
//                        om.setOrderCounts(outs);
//                        res.add(om);
//                    }

//                    if (cabinet.size() != 0) {
//                        OrderVOMax om = new OrderVOMax();
//                        BeanUtils.copyProperties(take, om);
//                        om.setId(id - 2 * id - 2);
//                        om.setOrderStatus(-23);
//                        om.setOrderCounts(cabinet);
//                        res.add(om);
//                    }

                }
            }

        }

        for (Order order1 : order) {
            OrderVOMax o = new OrderVOMax();
            o.setId(order1.getId());
            o.setNumber(order1.getNumber());
            o.setOrderStatus(order1.getOrderStatus());
            o.setImageOver(order1.getImageOver());
            o.setCount(order1.getCount());
            o.setRemark(order1.getRemark());
            o.setPhone(order1.getPhone());
            o.setPackageInfo(order1.getPackageInfo());
            o.setAddress(order1.getAddress());
            o.setImages(order1.getImages());
            o.setOrderCounts(order1.getOrderCounts());
            o.setOrderType(order1.getOrderType());
            takeRes.add(o);
        }

        takeRes.addAll(res);
        long end2 = end();
        System.out.println("虚拟单所有信息：" + (end2 - start2));


        return takeRes;
    }


    @Transactional
    public synchronized Result take(Integer id, Integer received) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            return Result.error("id错误");
        }
        List<OrderCount> orderCounts = orderCountMapper.selectByOrderId(id);
        if (orderCounts == null || orderCounts.size() == 0) {
//            Long number = orders.getNumber();
//            LocalDateTime now = LocalDateTime.now();
//            orderMapper.updateCollected(id, received);
//            orderMapper.updateTime(id, now);
//            orderMapper.updateTakeTime(number, now);
            return Result.error("非法数据，取件码不存在");
        } else {
            for (OrderCount orderCount : orderCounts) {
                Integer takeStatus = orderCount.getTakeStatus();
                if (takeStatus != 3) {
                    return Result.error("未完成取件！");
                }
            }
            Long number = orders.getNumber();
            LocalDateTime now = LocalDateTime.now();
            orderMapper.updateCollected(id, received);
            orderMapper.updateTime(id, now);
            orderMapper.updateTakeTime(number, now);
            return Result.success("取件成功");
        }

    }

    /**
     * 已送达
     *
     * @param id
     * @param reached
     * @return
     */
    @Override
    @Transactional
    public Result arrive(Integer id, Integer reached) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            return Result.error("id错误");
        }

        try {
            Long number = orders.getNumber();
            LocalDateTime now = LocalDateTime.now();
            orderMapper.updateReached(id, reached);
            orderMapper.updateTime(id, now);
            orderMapper.updateDeliveryTime(number, now);
            return Result.success("送达成功");
        } catch (Exception e) {
            return Result.error("请不要挑战我！");
        }

    }


    /**
     * 根据时间段查询
     *
     * @param start
     * @param end
     * @return
     */
    public List<OrderVOMax> selectByTime(Long start, Long end) {
        LocalDateTime s = timestamToDatetime(start);
        LocalDateTime e = timestamToDatetime(end);
        List<OrderVOMax> list = orderMapper.selectByTime(s, e);
        return list;
    }


    /**
     * 送达后上传图片
     *
     * @param id
     * @param image
     */
    public void image(Integer id, MultipartFile image) {
        //获取图片资源数组
        MultipartFile[] files = {image};
        //创建集合对象
        List<String> imgs = new ArrayList<>();
        //存储到本地
        uploadToLocal(files, imgs);
        orderMapper.updateImage(imgs.get(0), id);
    }


    public void download(String url, HttpServletResponse response) {
        if (url != null && url != "") {
            download(basePath, url, response);
        }
    }

    /**
     * 标记为疑难件
     *
     * @param id
     * @return
     */

    public synchronized Result fail(Integer id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            return Result.error("id错误");
        }
        LocalDateTime now = LocalDateTime.now();
        orderMapper.updateTime(id, now);
        orderMapper.updateFail(id);
        return Result.success("已标记为疑难件");
    }


    /**
     * 查询昨天七点后的订单
     *
     * @return
     */
    public List<Orders> selectOrders() {

        String kf = "oD1dE6RdILU9O-EXNaaOSc4cK2-g";

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd");
        DateTimeFormatter fmtLocalDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate today = LocalDate.now();
        String today_ = today.format(fmt);
        String today__ = today.format(fmtLocalDate);

        String[] split = today_.split("-");

        String s = split[1];
        int n1 = Integer.parseInt(s);

        if (n1 < 10) {
            today_ = split[0] + "-" + n1;
        }
//
//        String[] split1 = today__.split("-");
//        String s1 = split1[2];
//
//        int n2 = Integer.parseInt(s1);
//        if (n2 < 10) {
//            today__ = split1[0] + split1[1] + "-" + n2;
//        }

        List<Orders> list = orderMapper.selectByExpectTime(today_);
//        List<Orders> list = orderMapper.selectByExpectTime("12-2");

        List<Orders> list1 = orderMapper.selectByCreateTime(today__);
//        List<Orders> list1 = orderMapper.selectByCreateTime("12-2");

        list.addAll(list1);
//        LocalDate yesterday = today.plusDays(-1);
//
//        String yesterdayStr = yesterday.format(fmtLocalDate);
//
//        String start = yesterdayStr + " 19:00:00";
//        DateTimeFormatter fmtLocalDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime startTime = LocalDateTime.parse(start, fmtLocalDateTime);

//        List<Orders> list = orderMapper.selectOrders(startTime);
        List<Orders> res = new ArrayList<>();

        Integer[] states = new Integer[]{-3, 6, 2, 21, 22, 23, 24, 25, 1, -2, 3, 4, 5};
//        Arrays.sort(states);

        for (Integer state : states) {
            for (Orders orders : list) {
                if (orders.getOrderStatus().equals(state)) {

                    Long number = orders.getNumber();

                    TakeOrders takeOrders = takeOrderMapper.selectByNumber(number);
                    orders.setJudged(false);

                    if (takeOrders != null) {
                        String openid = takeOrders.getOpenid();
                        if(openid.equals(kf)){
                            orders.setJudged(true);
                        }
                    }else {
                        orders.setJudged(null);
                    }

                    res.add(orders);
                }
            }
        }
        return res;
    }

    /**
     * 更新订单状态为21
     *
     * @param id
     * @return
     */
    public synchronized Result update21(Integer id) {
        try {
            Orders orders = orderMapper.selectById(id);
            if (orders == null) {
                return Result.error("id错误");
            }
            LocalDateTime now = LocalDateTime.now();
            orderMapper.update(id, now, 21);
            return Result.success();
        } catch (Exception e) {
            return Result.error("数据异常");
        }
    }

    /**
     * 更新订单状态为22
     *
     * @param id
     * @return
     */
    public synchronized Result update22(Integer id) {
        try {
            Orders orders = orderMapper.selectById(id);
            if (orders == null) {
                return Result.error("id错误");
            }
            LocalDateTime now = LocalDateTime.now();
            orderMapper.update(id, now, 22);
            return Result.success();
        } catch (Exception e) {
            return Result.error("数据异常");
        }
    }


    /**
     * 更新订单状态为23
     *
     * @param id
     * @return
     */
    public synchronized Result update23(Integer id) {
        try {
            Orders orders = orderMapper.selectById(id);
            if (orders == null) {
                return Result.error("id错误");
            }
            LocalDateTime now = LocalDateTime.now();
            orderMapper.update(id, now, 23);
            return Result.success();
        } catch (Exception e) {
            return Result.error("数据异常");
        }
    }

    /**
     * 更新订单状态为-3
     *
     * @param id
     * @return
     */
    public synchronized Result updatef3(Integer id) {
        try {
            Orders orders = orderMapper.selectById(id);
            if (orders == null) {
                return Result.error("id错误");
            }
            LocalDateTime now = LocalDateTime.now();
            orderMapper.update(id, now, -3);
            return Result.success();
        } catch (Exception e) {
            return Result.error("数据异常");
        }
    }

    /**
     * 更新订单件数
     *
     * @param id
     * @return
     */
    public synchronized Result updateCount(Integer id, Integer count) {
        try {
            Orders orders = orderMapper.selectById(id);
            if (orders == null) {
                return Result.error("id错误");
            }
            LocalDateTime now = LocalDateTime.now();
            orderMapper.updateCount(id, count, now);
            return Result.success();
        } catch (Exception e) {
            return Result.error("数据异常");
        }

    }

    /**
     * 更新订单状态为6
     *
     * @param id
     * @return
     */
    @Transactional
    public synchronized Result update6(Integer id) {
        try {
            Orders orders = orderMapper.selectById(id);
            if (orders == null) {
                return Result.error("id错误");
            }
            if (orders.getOrderStatus() == 6) {
                return Result.error("不要重复操作");
            }
            Long id1 = orders.getId();
            List<OrderCount> orderCounts = orderCountMapper.selectByOrderId(Math.toIntExact(id1));
            if (orderCounts != null && orderCounts.size() == 1) {
                return Result.error("无法执行此操作");
            }
            if (orderCounts != null && orderCounts.size() != 0) {
                for (OrderCount orderCount : orderCounts) {
                    if (orderCount.getTakeStatus() == 2) {
                        return Result.error("请先确定小件的状态");
                    }
                }
                Integer res = 0;
                for (OrderCount orderCount : orderCounts) {
                    if (orderCount.getTakeStatus() == 3) {
                        res++;
                    }
                }
                if (res == orderCounts.size()) {
                    return Result.error("请点击已取件");
                }

            }


            LocalDateTime now = LocalDateTime.now();
            orderMapper.update(id, now, 6);
            return Result.success();
        } catch (Exception e) {
            return Result.error("数据异常");
        }
    }

    @Transactional
    public synchronized Result update2(Integer id) {

//        Orders orders = orderMapper.selectById(id);
//
//        if (orders == null) {
//            return Result.error("id错误");
//        }
//
//        Integer orderStatus = orders.getOrderStatus();
//
//        if (orderStatus != 21 && orderStatus != 22 && orderStatus != 23 && orderStatus != -2) {
//            return Result.error("无法执行此操作");
//        }
//
//        if (orderStatus == 2) {
//            return Result.error("无法执行此操作");
//        }
//        orderMapper.update(id, LocalDateTime.now(), 2);
        return Result.error("该功能不开放!");
    }

    /**
     * 查询所有已完成的订单
     *
     * @return
     */
    public Result<List<ImageOverVO>> selectImgOvers() {

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd");
        DateTimeFormatter fmtLocalDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate today = LocalDate.now();
        String today_ = today.format(fmt);
        String today__ = today.format(fmtLocalDate);

        List<Orders> list = orderMapper.selectByExpectTime(today_);
//        List<Orders> list = orderMapper.selectByExpectTime("11-19");
        List<Orders> list1 = orderMapper.selectByCreateTime(today__);
//        List<Orders> list1 = orderMapper.selectByCreateTime("11-19");

        list.addAll(list1);
//        LocalDate yesterday = today.plusDays(-1);
//
//        String yesterdayStr = yesterday.format(fmtLocalDate);
//
//        String start = yesterdayStr + " 19:00:00";
//        DateTimeFormatter fmtLocalDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime startTime = LocalDateTime.parse(start, fmtLocalDateTime);

//        List<Orders> list = orderMapper.selectOrders(startTime);
//        List<Orders> res = new ArrayList<>();
//
//        Integer[] states = new Integer[]{-3, 6, 2, 21, 22, 23, 1, -2, 3, 4, 5};
////        Arrays.sort(states);
//        for (Integer state : states) {
//            for (Orders orders : list) {
//                if (orders.getOrderStatus() == state) {
//                    res.add(orders);
//                }
//            }
//        }

        List<ImageOverVO> res = list.stream().map(orders -> ImageOverVO.builder().orderNumber(orders.getNumber()).imgUrl(orders.getImageOver() == null ? null : serverPath + orders.getImageOver()).build()).collect(Collectors.toList());
        List<ImageOverVO> collect = res.stream().filter(imageOverVO -> imageOverVO.getImgUrl() != null).collect(Collectors.toList());
        return Result.success(collect);
    }


    public Result<List<ImageOverVO>> selectIOsByTime(Integer id) {

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd");
        DateTimeFormatter fmtLocalDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter localTimeFormat = DateTimeFormatter.ofPattern("HH:mm");

        LocalDate today = LocalDate.now();
        String today_ = today.format(fmt);
        String today__ = today.format(fmtLocalDate);

        String[] split = today_.split("-");
        String s = split[1];
        int i = Integer.parseInt(s);

        if (i < 10) {
            today_ = split[0] + "-" + i;
        }

        List<Orders> list = orderMapper.selectByExpectTime(today_);
//        List<Orders> list = orderMapper.selectByExpectTime("11-20");
//        List<Orders> list1 = orderMapper.selectByCreateTime(today__);
//        List<Orders> list1 = orderMapper.selectByCreateTime("11-20");

//        list.addAll(list1);

        list.stream().forEach(new Consumer<Orders>() {
            @Override
            public void accept(Orders orders) {
                String expectTime = orders.getExpectTime();
                if (expectTime != null) {
                    String substring = expectTime.substring(0, 5);
                    String substring1 = expectTime.substring(5);
                    String[] split1 = substring.split("-");
                    if (split1.length != 1) {
                        int i1 = Integer.parseInt(split1[1].trim());
                        if (i1 < 10) {
                            orders.setExpectTime(split1[0] + "-" + "0" + i1 + " " + substring1);
                        }
                    }
                }

            }
        });

        switch (id) {

            case 0: {
                List<ImageOverVO> res = list.stream()
                        .map(orders -> ImageOverVO.builder().orderNumber(orders.getNumber()).imgUrl(orders.getImageOver() == null ? null : serverPath + orders.getImageOver()).build())
                        .filter(imageOverVO -> imageOverVO.getImgUrl() != null)
                        .collect(Collectors.toList());
                return Result.success(res);
            }

            case 1: {
                List<ImageOverVO> res = list.stream()
                        .filter(orders -> LocalTime.parse(orders.getExpectTime().substring(6, 11), localTimeFormat).compareTo(LocalTime.of(12, 0, 0)) <= 0)
                        .map(orders -> ImageOverVO.builder().orderNumber(orders.getNumber()).imgUrl(orders.getImageOver() == null ? null : serverPath + orders.getImageOver()).build())
                        .filter(imageOverVO -> imageOverVO.getImgUrl() != null)
                        .collect(Collectors.toList());
                return Result.success(res);
            }

            case 2: {
                List<ImageOverVO> res = list.stream()
                        .filter(orders -> LocalTime.parse(orders.getExpectTime().substring(6, 11), localTimeFormat).compareTo(LocalTime.of(12, 0, 0)) > 0)
                        .map(orders -> ImageOverVO.builder().orderNumber(orders.getNumber()).imgUrl(orders.getImageOver() == null ? null : serverPath + orders.getImageOver()).build())
                        .filter(imageOverVO -> imageOverVO.getImgUrl() != null)
                        .collect(Collectors.toList());
                return Result.success(res);
            }
        }

        return null;
    }

    /**
     * 打回订单
     *
     * @param id
     * @return
     */
    @Transactional
    public Result repulse(Integer id) {

        Orders orders = orderMapper.selectById(id);


        //更新productid 为13 订单状态为1
        orderMapper.updateById(id);

        //将接单表的信息删除
        takeOrderMapper.deleteByNumber(orders.getNumber());

        //取件码删除
        orderCountMapper.deleteByOrderId(id);

        //虚拟单删除
        fakeMapper.deleteByOrderId(id);

//        return Result.error("error");
        return Result.success("success");
    }

    /**
     * 给前台增加错误信息
     *
     * @param id
     * @param errorMsg
     * @return
     */
    @Transactional
    public Result updateErrorMsg(Integer id, String errorMsg) {
        orderMapper.update(id, LocalDateTime.now(), -5);
        orderMapper.updateMsg(id, errorMsg);
        return Result.success();
    }


    public void download(String basePath, String url, HttpServletResponse response) {
        try {
            //服务器上的图片路径
            String fileImg = basePath + url;
            FileInputStream fileInputStream = new FileInputStream(fileImg);
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public LocalDateTime timestamToDatetime(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    public static String getNum(String str) {
        String dest = "";
        if (str != null) {
            dest = str.replaceAll("[^0-9]", "");

        }
        return dest;
    }

    /**
     * 订单文件上传到本地
     *
     * @param files
     * @param imgs
     */
    @Transactional
    public void uploadToLocal(MultipartFile[] files, List<String> imgs) {
        for (int i = 0; i < files.length; i++) {
            String filePath = upload(basePath, files[i]);
            imgs.add(filePath);
        }
    }

    public String upload(String basePath, MultipartFile img) {
        try {
            String originalFilename = img.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString().replace("-", "") + extension;

            //创建一个目录对象
            File dir = new File(basePath);
            //没有目录则创建
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String filePath = basePath + objectName;
            img.transferTo(new File(filePath));
            return objectName;
        } catch (IOException e) {
            log.info("文件上传失败");
            return null;
        }
    }

    public long start() {
        return System.currentTimeMillis();
    }

    public long end() {
        return System.currentTimeMillis();
    }

    public long exe(long start, long end) {
        return System.currentTimeMillis();
    }


}
